package Lock;


import java.util.concurrent.locks.ReentrantLock;

public class LockExample {
    private final ReentrantLock lock = new ReentrantLock();
    private int counter = 0;

    public static void main(String[] args) {
        LockExample lockExample = new LockExample();
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                lockExample.increment();
            }
        });
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                lockExample.increment();
            }
        });
        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println("result=" + lockExample.getcount());
    }

    public void increment() {
        lock.lock();//获取锁
        try {
            counter++;
        } finally {
            lock.unlock();//释放锁
        }

    }

    public int getcount() {
        lock.lock();
        try {
            return counter;
        } finally {
            lock.unlock();
        }
    }
}